import os
import cairosvg
from lxml import etree
from svglib.svglib import svg2rlg
from reportlab.graphics import renderPM
from utils.platform import *
from settings import *

def svg2png(dwg, content_width, content_height, svg_file_path, png_file_path):
    dwg.save()

    # replace size
    svg_file = svg_file_path
    with open(svg_file, 'rb') as f:
        svg_data = f.read()
        parser = etree.XMLParser(remove_blank_text=True)
        svg_tree = etree.fromstring(svg_data, parser)

    for element in svg_tree.iter():
        if 'height' in element.attrib:
            element.attrib['height'] = element.attrib['height'].replace('100%', '{}'.format(content_height))
        if 'width' in element.attrib:
            element.attrib['width'] = element.attrib['width'].replace('100%', '{}'.format(content_width))

    # save svg
    with open(svg_file_path, 'wb') as f:
        f.write(etree.tostring(svg_tree, pretty_print=True))

    # save as png
    if is_windows():
        cairosvg.svg2png(url=svg_file_path, write_to=png_file_path)
    elif is_darwin():
        drawing = svg2rlg(svg_file_path)
        image = renderPM.drawToPIL(d=drawing, bg=0xff00ff)
        image = image.convert('RGBA')
        data = image.getdata()
        new_data = [(255, 255, 255, 0) if item[:3] == (255, 0, 255) else item for item in data]
        image.putdata(new_data)
        image.save(png_file_path, fmt='PNG')
    else:
        exit(-1)

    os.remove(svg_file_path)